package by.grsu.epam.service.entitiesservice.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import by.grsu.epam.dao.entitiesdao.UserDAO;
import by.grsu.epam.domain.user.UserRole;

@Service
public class MyUserDetailsService implements UserDetailsService {
	
	@Autowired
	UserDAO userDAO;

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		by.grsu.epam.domain.user.User domainUser = userDAO.findByUsername(username);
		
		String password = domainUser.getPassword();
		boolean isNotLocked = domainUser.getSubscriberIsNotLocked();
		List<GrantedAuthority> grantedAuth = getGrantedAuthorities(userDAO.findRolesById(domainUser.getId()));
		
		return new User(username, password, isNotLocked, isNotLocked, isNotLocked, isNotLocked, grantedAuth);
	}
	
	public static List<GrantedAuthority> getGrantedAuthorities(List<UserRole> roles) {  
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();  
          
        for (UserRole role : roles) {  
            authorities.add(new SimpleGrantedAuthority(role.getAuthority()));  
        }  
        return authorities;  
    }  

}
